import { defineEventHandler, getQuery } from 'h3'
import redis from '../../util/redis'
import { checkAdminKey } from './_utils'
import { recordLog } from '../../util/log'

export default defineEventHandler(async (event: any) => {
  const ck = await checkAdminKey(event)
  if (!ck.ok) return { status: event.node.res.statusCode || 401, message: ck.message }

  try {
    const q = getQuery(event) as any
    const key = q?.key ?? ''
    if (!key || typeof key !== 'string') {
      event.node.res.statusCode = 400
      return { status: 400, message: 'missing key' }
    }

    const value = await (redis as any).get(`ym:${key}`)
    await recordLog(event as any, { message: `admin/ym: get key=${key} result=${value ? 'found' : 'notfound'}`, userId: 0 })
    if (value === null) {
      event.node.res.statusCode = 404
      return { status: 404, message: 'not found' }
    }
    try {
      const obj = JSON.parse(value)
      return { status: 'ok', key, data: obj }
    } catch (e) {
      return { status: 'ok', key, data: { raw: value } }
    }
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event as any, { message: `admin/ym: get failed ${String(err)}`, userId: 0 })
    return { status: 500, message: 'redis get failed', error: String(err) }
  }
})
